<?php

namespace app\admin\controller;

use app\model\NewsModel;
use think\Db;
use think\Request;

class News extends Base
{
    public function __construct(Request $app)
    {
        $this->model = NewsModel::class;
        parent::__construct($app);
    }

    public function queryWhere()
    {
        if(!empty($this->param['title'])){
            $this->param['title'] = ['like','%'.$this->param['title'].'%'];
        }
        return parent::queryWhere();
    }


    public function beforeUpdate($param, $id)
    {
        unset($param['file']);
        $param['pre_content'] = trim($param['pre_content']);
        $param['pre_content'] = preg_replace('# #', '',$param['pre_content']);
        $param['pre_content'] = mb_substr($param['pre_content'],0,50).'...';
        return parent::beforeUpdate($param, $id); // TODO: Change the autogenerated stub
    }


    public function beforeAdd($param)
    {
        unset($param['file']);
        $param['pre_content'] = trim($param['pre_content']);
        $param['pre_content'] = preg_replace('# #', '',$param['pre_content']);
        $param['pre_content'] = mb_substr($param['pre_content'],0,50).'...';
        $param['status'] = 1;
        return parent::beforeAdd($param); // TODO: Change the autogenerated stub
    }


    /**
     * 公共上传
     * @return \think\response\Json
     */
    public function upload()
    {
        $file = $this->request->file('file');
        if($file){
            $move = ROOT_PATH.'/public/static/upload/';
            $res = $file->move($move,true,false);
            $data = [
                'src' => '/static/upload/'.$res->getSaveName() ,
            ];
            if($res){
                return $this->success($data,'上传成功',0);
            } else{
                return $this->error([],'上传失败');
            }
        }else{
            return $this->error([],'上传失败');
        }
    }

}